package com.quanyue.haircut.user.service.impl;

import com.quanyue.auto.util.AssertUtils;
import com.quanyue.auto.wechat.service.MerchantService;
import com.quanyue.haircut.domain.entity.HaircutMerchant;
import com.quanyue.haircut.user.dto.MerchantDetail;
import com.quanyue.haircut.user.mapper.HaircutMerchantMapper;
import com.quanyue.haircut.user.service.HaircutMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class HaircutMerchantServiceImpl implements HaircutMerchantService {
    @Autowired
    private HaircutMerchantMapper merchantMapper;
    @Autowired
    private MerchantService merchantService;

    @Override
    @Transactional
    public void addMerchant(HaircutMerchant merchant) {
        merchant.setCreateTime(LocalDateTime.now());
        merchant.setModifyTime(LocalDateTime.now());
        merchant.setDelFlag(false);
        merchantMapper.insert(merchant);
        com.quanyue.auto.wechat.domain.Merchant autoMerchantNo = null;
        autoMerchantNo.setCreateBy(merchant.getId().toString());
        autoMerchantNo.setForbidden(true);
        autoMerchantNo.setMerchantNo(merchant.getMerchantNo());
        autoMerchantNo.setName("init");
        autoMerchantNo.setCreateTime(LocalDateTime.now());
        autoMerchantNo.setModifyTime(LocalDateTime.now());
        merchantService.add(autoMerchantNo);
    }

    @Override
    public void updateMerchant(HaircutMerchant merchant) {
        HaircutMerchant check = merchantMapper.findOne(merchant.getId());
        AssertUtils.notNull(check, "没有该商户");
        merchant.setCreateTime(check.getCreateTime());
        merchant.setModifyTime(LocalDateTime.now());
        merchant.setMerchantNo(check.getMerchantNo());
        merchant.setDelFlag(false);
        merchantMapper.updateSelective(merchant);
    }

    @Override
    public void deleteMerchant(Integer id) {
        merchantMapper.deleteOne(id);
    }

    @Override
    public HaircutMerchant selectMerchantByNo(Integer merchantNo) {
        return merchantMapper.findByMerchantNo(merchantNo);
    }

    @Override
    public List <MerchantDetail> selectMerchantList(Integer fatherId) {
        List <MerchantDetail> merchantDetails = merchantMapper.findByFatherId(fatherId);
        merchantDetails.forEach(merchantDetail -> {
            merchantDetail.setMerchantTurnover(merchantMapper.findTurnoverByMerchant(merchantDetail.getMerchantNo()));
        });
        return merchantDetails;
    }
}
